package com.ruoyi.web.core.config;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;

import java.util.function.Predicate;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(
                        "com.ruoyi.backend.controller",
                        "com.ruoyi.scheme.controller"
                ))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 支持多个包扫描
     */
    public static Predicate<RequestHandler> basePackage(String... basePackages) {
        return requestHandler -> {
            Class<?> declaringClass = requestHandler.declaringClass();
            if (declaringClass == null) {
                return false;
            }
            String packageName = declaringClass.getPackage().getName();
            for (String basePackage : basePackages) {
                if (packageName.startsWith(basePackage)) {
                    return true;
                }
            }
            return false;
        };
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("若依-Ruoyi API文档")
                .description("详细的接口文档说明")
                .version("1.0.0")
                .contact(new Contact("联系人", "https://ruoyi.vip/", "邮箱"))
                .build();
    }
}
